const config = require('./config');
import koa from 'koa';
import pathUtils from './utils/pathUtils';
import { Lifetime, createContainer, asClass } from 'awilix'; // IOC容器
import { scopePerRequest, loadControllers } from 'awilix-koa'; // IOC路由组件
import bodyParser from 'koa-bodyparser'; //解析POST数据请求
import { loginit } from './log4js'; // 打印错误日志配置

const app = new koa();

// ioc容器注入
const container = createContainer();
container.loadModules(['models/**/*'], {
  cwd: pathUtils.appDir(),
  // 会把驼峰转换  这样`TodosService`转成`todosService`.
  formatName: 'camelCase',
  resolverOptions: {
    lifetime: Lifetime.SCOPED, // 设置有作用域
    register: asClass,
  },
});
app.use(scopePerRequest(container)); // 容器挂载到use中间件
app.use(bodyParser()); // 解析POST数据请求
loginit(app); // 记录错误日志

// 路由中间件
app.use(
  loadControllers(pathUtils.appDir('/controllers/**/*'), {
    cwd: pathUtils.appDir(), // 指定目录路径
  })
);

const server = app.listen(config.port, () => {
  console.log(`服务启动成功 http://localhost:${config.port}`);
});

export default {
  app,
  server,
};
